"""
设备管理定时任务初始化脚本
用于添加设备管理相关的定时任务到系统中
"""
import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.database import DatabaseManager
from common.config import settings


def init_scheduled_tasks():
    """初始化设备管理定时任务"""
    db = DatabaseManager()

    try:
        # 检查是否已存在RTU心跳检测任务
        check_sql = "SELECT id FROM base_scheduled_task WHERE task_code = %s"
        existing = db.execute_query(check_sql, ("rtu_heartbeat_check",))

        if existing:
            print("RTU心跳检测任务已存在，跳过初始化")
        else:
            # 插入RTU心跳检测任务
            insert_sql = """
                INSERT INTO base_scheduled_task (task_code, task_name, task_type, cron_expression,
                                               task_handler, enabled, description)
                VALUES (%s, %s, %s, %s, %s, %s, %s)
            """

            db.execute_query(insert_sql, (
                "rtu_heartbeat_check",
                "RTU心跳检测",
                "SYSTEM",
                "0 */30 * * * ?",  # 每30分钟执行一次
                "device.task.rtu_heartbeat_check",
                1,
                "自动检测RTU心跳，超时设为OFFLINE"
            ), commit=True)

            print("RTU心跳检测任务初始化成功")

        # 检查是否已存在电表检定提醒任务
        check_sql = "SELECT id FROM base_scheduled_task WHERE task_code = %s"
        existing = db.execute_query(check_sql, ("meter_calibration_reminder",))

        if existing:
            print("电表检定提醒任务已存在，跳过初始化")
        else:
            # 插入电表检定提醒任务
            insert_sql = """
                INSERT INTO base_scheduled_task (task_code, task_name, task_type, cron_expression,
                                               task_handler, enabled, description)
                VALUES (%s, %s, %s, %s, %s, %s, %s)
            """

            db.execute_query(insert_sql, (
                "meter_calibration_reminder",
                "电表检定提醒",
                "SYSTEM",
                "0 0 9 * * ?",  # 每天上午9点执行
                "device.task.meter_calibration_reminder",
                1,
                "自动提醒calibration_due_date到期电表"
            ), commit=True)

            print("电表检定提醒任务初始化成功")

    except Exception as e:
        print(f"初始化定时任务失败: {e}")
        raise
    finally:
        db.close()


if __name__ == "__main__":
    init_scheduled_tasks()